import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.Socket;
import java.net.SocketException;


public class SIPListener extends Thread{
	
	private Socket socket =  null;
	private BufferedReader in;
	private PrintWriter out;
	private final static int timeout = 10000;
	private int status;
	private byte[] buf;
	
	public SIPListener(Socket socket) throws IOException{
		this.socket = socket;
		init();
		

	}
	
	private void init() throws IOException{
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
		status = SIPEngine.WAIT;
		buf = new byte[ChatServer.bufsize];
	}
	
	public void run(){
		String line;
		try {
			while (!(line = in.readLine()).equalsIgnoreCase("BYE")){
				System.out.println(line);
				if(line.matches("^INVITE.*")){
					sendMsg("200OK");
				}else if(line.matches("^ACK")){
					Member.addrList.add(socket.getInetAddress());
					DatagramPacket packet = new DatagramPacket(buf,0,buf.length, socket.getInetAddress(),UdpHandler2.PEER_UDP_PORT);
					Member.packetlist.add(packet);
					System.out.println("A client is added!");
				}
			}
			
			leave();
			
		} catch (IOException e) {
			leave();
		} catch (NullPointerException e){
			leave();
		}
			
		
	}
	
	private void leave(){
		try {
			in.close();
			out.close();
			Member.packetlist.remove(Member.addrList.indexOf(socket.getInetAddress()));
			Member.addrList.remove(socket.getInetAddress());
			socket.close();
			System.out.println("a client left!");
		} catch (IOException e) {
			Member.packetlist.remove(Member.addrList.indexOf(socket.getInetAddress()));
			Member.addrList.remove(socket.getInetAddress());
			System.out.println("a client left!");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void sendMsg(String str){
		out.println(str);
		out.flush();
	}

}
